package com.triplelink.context;

import org.openrdf.model.Literal;
import org.openrdf.model.URI;
import org.openrdf.model.ValueFactory;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.base.RepositoryBase;

import com.triplelink.annotations.DatatypeProperty;
import com.triplelink.enums.Transaction;

public class UserConnector
{
	private Connector connector;
	private boolean ownerConnection = false;
	private Transaction transaction;
	private ValueFactory valueFactory;

	protected ValueFactory getValueFactory ()
	{
		if (valueFactory == null) {
			
			valueFactory = getRepositoryBase().getValueFactory();
		}
		
		return valueFactory;
	}
	
	public UserConnector(Connector connector)
	{
		this.connector = connector;
	}
	
	protected Connector getConnector() {

		if (transaction == Transaction.REQUERIDE)
			getConnection();
		
		return connector;
	}
	
	protected RepositoryConnection getConnection()
	{
		tryGetTitleOwner();
		
		return connector.getConnection();
	}
	
	private void tryGetTitleOwner()
	{
		if (!connector.isConnectionOpen())
			ownerConnection = true;
	}
	
	protected void closeConnection()
	{
		if (ownerConnection)
			connector.closeConnection();
	}
	
	public RepositoryBase getRepositoryBase()
	{
		return connector.getRepositoryBase();
	}
	
	protected URI createURI(String uriString)
	{
		return getValueFactory().createURI(uriString);
	}
	
	protected Literal createLiteral(String value, DatatypeProperty datatypeProperty)
	{
		return getValueFactory().createLiteral(value, createURI(datatypeProperty.range().val));
	}
}